package com.java.actual.chatroom;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ClientFrame extends JFrame{
	private JTextArea area;
	private JLabel label;
	private JTextField field;
	private JButton button;
	private String userName;
	private ChatRoomClient client;
	
	public ClientFrame(){
		//?????
		super("网络聊天室");
		do {
			String hostAddress = JOptionPane.showInputDialog(this, "请输入服务器地址：");
			if (hostAddress == null) {
				System.exit(0);
			}
			try {
				client = new ChatRoomClient(hostAddress, 8888);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(this, "无法建立与服务器端的连接！请检查网络");
			}
		} while (client==null);	
		String str=JOptionPane.showInputDialog(this,"请输入用户名：");
		this.userName=str.trim();
		area=new JTextArea(20,40);
		area.setEditable(false);
		label=new JLabel();
		field=new JTextField(25);
		this.button=new JButton("发送");
		init();
	}
	
	public void init(){
		//??????
		JScrollPane jsp=new JScrollPane(area);
		this.setLayout(new BorderLayout());
		this.add(jsp,BorderLayout.CENTER);
		Panel panelSouth=new Panel();
		panelSouth.setLayout(new FlowLayout());
		panelSouth.add(label);
		panelSouth.add(field);
		panelSouth.add(button);
		this.add(panelSouth,BorderLayout.SOUTH);
		field.setFont(new Font("宋体",Font.BOLD,15));
		this.label.setText(this.userName);
		
		addEventHandler();
		
	}
	
	public void addEventHandler(){
		//????
		this.addWindowListener(new WindowAdapter(){

			public void windowClosing(WindowEvent e) {
				int p=JOptionPane.showConfirmDialog(ClientFrame.this,"你确定要离开聊天室吗？","确认退出",JOptionPane.YES_NO_OPTION);
				if(p==JOptionPane.YES_OPTION){
					client.sendMessage("%EXIT%:"+userName);
					try {
						Thread.sleep(200);
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					client.close();
					System.exit(0);
					
				}
			}
		});
		button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				client.sendMessage(ClientFrame.this.userName+":"+field.getText());
				field.setText("");
			}
		});
	}
	
	public void showMe(){
		//?????
		this.pack();
		this.setVisible(true);
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		new ReadMessageThread().start();
	}
	
	private class ReadMessageThread extends Thread{
		public void run(){
			while(true){
				String str=client.reciveMessage();
				area.append(str+"\n");
			}
		}
	}
	
	public static void main(String[] args){
		new ClientFrame().showMe();
	}

}

